Hash functions are located in the "hashlib" module. Note that hash() is a built-in Python function that doesn't have much to do with generating hashed values.


In [ ]:
import hashlib
print hashlib.algorithms

Verifying File Checksums


In [ ]:
iso_file = '/Users/mwedgwood/repos/eops-py-course/downloads/CentOS-6.5-x86_64-netinstall.iso'
sums = {
    'md5': '939fd1d87c11ffe7795324438b85adfb',
    'sha1': '3a9662cb65f9d59677d76acfdb73289da43b4599',
    'sha256': 'd8aaf698408c0c01843446da4a20b1ac03d27f87aad3b3b7b7f42c6163be83b9',
}

In [ ]:
for hashtype in sums:
    hashobj = getattr(hashlib, hashtype)()
    with open(iso_file) as data:
        hashobj.update(data.read())
    digest = hashobj.hexdigest()
    print digest
    print sums[hashtype]
    if digest == sums[hashtype]:
        print "{} matches".format(hashtype)
    else:
        print "**** {} does not match ****".format(hashtype)
    print

Generating Password Hashes

Adapted from http://throwingfire.com/storing-passwords-securely/


In [ ]:
import os
import base64

salt = base64.b64encode(os.urandom(32))
print salt

In [ ]:
password = 's3kr3t!!1'

def get_digest(password, salt=None):
    rounds = 5000
    secret_key = 'notsafe'
    if not salt:
        salt = base64.b64encode(os.urandom(32))
    digest = password
    for i in xrange(rounds):
        digest = hashlib.sha512(salt + digest + secret_key).hexdigest()
    return salt, digest

salt, digest = get_digest(password)
print salt
print digest

How long did that take?


In [ ]:
import timeit
print timeit.timeit('get_digest(password)', setup='from __main__ import password, get_digest', number=1000)